package com.xijiekou.sifasuomax.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.xijiekou.sifasuomax.R;
import com.xijiekou.sifasuomax.adapter.NewOralAdapter;
import com.xijiekou.sifasuomax.bean.NewOralBean;
import com.xijiekou.sifasuomax.bean.NewOralBeans;
import com.xijiekou.sifasuomax.bean.PostRequestBean;
import com.xijiekou.sifasuomax.dialog.CommonDialog;
import com.xijiekou.sifasuomax.model.BaseModel;
import com.xijiekou.sifasuomax.model.CreateOralCaseIdModel;
import com.xijiekou.sifasuomax.model.ModifyOralModel;
import com.xijiekou.sifasuomax.model.NewOralModel;
import com.xijiekou.sifasuomax.model.PrintModel2;
import com.xijiekou.sifasuomax.model.SearchNewOralModel;
import com.xijiekou.sifasuomax.utils.BeanToJsonUtils;
import com.xijiekou.sifasuomax.utils.IntentUtils;
import com.xijiekou.sifasuomax.utils.SharePreferenceUtils;
import com.xijiekou.sifasuomax.utils.ToastUtils;
import com.xijiekou.sifasuomax.view.BottomConfirmView;
import com.xijiekou.sifasuomax.view.NoScrollListView;
import com.xijiekou.sifasuomax.view.VoiceEditTextView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.lang.ref.WeakReference;
import java.util.ArrayList;

/**
 * Created by zhouzhuo on 2017/7/4.
 * 口头协议
 */
public class NewOralActivity extends VoiceBaseActivity{
    private TextView tv_evidence_entering;
    private NoScrollListView listView;
    private ArrayList<NewOralBean> list;
    private TextView tv_add;
    private NewOralAdapter adapter;
    private NewOralBeans beans;
    private VoiceEditTextView rl_voiceView;
    private String caseId;
    private String search;
   // private String type ;//0 修改  1 查看
    private MyHandler handler;
    private BottomConfirmView bottom_confirm_view;
    private String audit;
    private class  MyHandler extends Handler{
        private WeakReference<NewOralActivity> reference;
        public MyHandler(NewOralActivity activity){
            reference = new WeakReference<>(activity);
        }
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if(reference.get()!=null){
                switch (msg.what){
                    case 0:
                        if(beans!=null&&beans.list!=null&&beans.list.size()>0){
                            adapter = new NewOralAdapter(NewOralActivity.this,list);
                            listView.setAdapter(adapter);
                        }
                        if(beans!=null){
                            rl_voiceView.setText(beans.argue);
                            rl_voiceView.setText2(beans.agreement);
                            rl_voiceView.setDate(beans.date);
                            rl_voiceView.setPerference(beans.performance);
                            rl_voiceView.setDate(beans.date);
                            rl_voiceView.setSign(beans.signature);
                            rl_voiceView.setNumber(beans.num);
                        }
                        break;
                }
            }
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_new_oral);
        initView();
        initData();
    }

    private void initData() {
        caseId = getIntent().getStringExtra("caseId");
        search = getIntent().getStringExtra("search");
        if(TextUtils.isEmpty(caseId)){
            //创建
            Log.d("zhouzhuo","==走的创建=");
            CreateOralCaseIdModel createOralCaseIdModel = new CreateOralCaseIdModel();
            createOralCaseIdModel.setCallBackListener(new BaseModel.CallBackListener<String>() {
                @Override
                public void success(String id) {
                    caseId = id;
                }

                @Override
                public void failed() {

                }
            });
            String id = (String) SharePreferenceUtils.get(this,"id","");
            String company =  (String) SharePreferenceUtils.get(this,"company","");
            createOralCaseIdModel.getCaseId(id,company);
            bottom_confirm_view.hidePrint();
        }else {
            //查看
            SearchNewOralModel model = new SearchNewOralModel();
            model.setCallBackListener(new BaseModel.CallBackListener<String>() {
                @Override
                public void success(String message)  {
                    try {
                        JSONObject object = new JSONObject(message);
                        int code = object.getInt("code");
                        if(code == 1){
                            search = "search";
                            JSONObject object1 = object.getJSONObject("data");
                            beans = new NewOralBeans();
                            beans.id = object1.getString("id");
                            beans.argue = object1.getString("argue");
                            audit = object1.getString("audit");
                            //兼容老数据  以后去掉 catch
                            try {
                                beans.agreement = object1.getString("agreement");
                            }catch (Exception e){
                                e.printStackTrace();
                            }

                            beans.performance = object1.getString("performance");
                            beans.signature = object1.getString("signature");
                            beans.date = object1.getString("date");
                            try{
                                beans.num = object1.getString("num");
                            }catch (Exception e){

                            }

                            try {
                                list = new ArrayList<>();
                                JSONArray array = object1.getJSONArray("persons");
                                Gson gson = new Gson();
                                for (int i=0;i<array.length();i++){
                                    NewOralBean bean = gson.fromJson(array.getJSONObject(i).toString(),NewOralBean.class);
                                    list.add(bean);
                                }
                                beans.list = list;
                            }catch (Exception e){
                                e.toString();
                            }
                            handler.sendEmptyMessage(0);

                        }else {
                            ToastUtils.showShort(NewOralActivity.this,object.getString("data"));

                        }

                    } catch (JSONException e) {
                        Log.d("zhouzhuo","查询口头异常=="+e.toString());
                        e.printStackTrace();
                    }
                }

                @Override
                public void failed() {

                }
            });
            model.searchOral(caseId);

        }

    }


    private void initView() {
        handler = new MyHandler(this);
        rl_voiceView = (VoiceEditTextView) findViewById(R.id.rl_voiceView);
        tv_add = (TextView) findViewById(R.id.tv_add);
        tv_add.setOnClickListener(this);
        tv_evidence_entering = (TextView) findViewById(R.id.tv_evidence_entering);
        tv_evidence_entering.setOnClickListener(this);
        bottom_confirm_view = (BottomConfirmView) findViewById(R.id.bottom_confirm_view);
        bottom_confirm_view.showSaveView();
        bottom_confirm_view.setConfirmListener(new BottomConfirmView.ConfirmListener() {
            @Override
            public void confirm() {
                Log.d("zhouzhuo","点击=confirm==");
                next();
            }
        });

        bottom_confirm_view.setSaveListener(new BottomConfirmView.SaveListener() {
            @Override
            public void save() {
                Log.d("zhouzhuo","点击save===");
                if(!TextUtils.isEmpty(audit)&&audit.equals("1")){
                    ToastUtils.showShort(NewOralActivity.this,"审核已经通过，不能操作");
                    return;
                }else {
                    NewOralBeans beans = getBean();
                    beans.isAudit = "1";
                    saveAndCreate(beans);
                }
            }
        });

        bottom_confirm_view.setPrintListener(new BottomConfirmView.PrintListener() {
            @Override
            public void print() {
                Log.d("zhouzhuo","点击=打印==");
                PrintModel2 model = new PrintModel2();
                NewOralBeans bean = getBean();
                String content = BeanToJsonUtils.part10(bean);
                Log.d("zhouzhuo","content:"+content);
                model.setCallBackListener(new BaseModel.CallBackListener<String>() {
                    @Override
                    public void success(String message) {
                        if(!TextUtils.isEmpty(message)&&message.equals("success")){
                            ToastUtils.showShort(NewOralActivity.this,"打印成功,请勿重复点击");
                        }else {
                            ToastUtils.showShort(NewOralActivity.this,"打印失败");
                        }
                    }

                    @Override
                    public void failed() {
                        ToastUtils.showShort(NewOralActivity.this,"打印失败,请检查打印服务是否开启");
                    }
                });
               String ip = (String) SharePreferenceUtils.get(NewOralActivity.this,"printIp","");
                if(TextUtils.isEmpty(ip)||ip.equals("1")){
                    ToastUtils.showShort(NewOralActivity.this,"暂不支持打印");
                }else {
                    model.print(content,"printB7",ip);
                }
            }
        });

        listView = (NoScrollListView) findViewById(R.id.lv_list);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                String type =list.get(position).type;
                switch (type){
                    case "1":
                        Intent intent1 = new Intent(NewOralActivity.this,AddOnePersonActivity.class);
                        intent1.putExtra("bean",list.get(position));
                        intent1.putExtra("position",position);
                        IntentUtils.startActivity(NewOralActivity.this,intent1,true,1);
                        break;
                    case "2":
                        intent1 = new Intent(NewOralActivity.this,AddTwoPersonActivity.class);
                        intent1.putExtra("bean",list.get(position));
                        intent1.putExtra("position",position);
                        IntentUtils.startActivity(NewOralActivity.this,intent1,true,2);
                        break;
                    case "3":
                        intent1 = new Intent(NewOralActivity.this,AddThreePersonActivity.class);
                        intent1.putExtra("bean",list.get(position));
                        intent1.putExtra("position",position);
                        IntentUtils.startActivity(NewOralActivity.this,intent1,true,3);
                        break;
                }
            }
        });
        listView.setDivider(getResources().getDrawable(R.drawable.new_oral_listview_divider));
        listView.setDividerHeight(15);

    }

    private NewOralBeans getBean(){
        beans = new NewOralBeans();
        beans.list = list;
        beans.id = caseId;
        beans.date = rl_voiceView.getDate();
        beans.argue = rl_voiceView.getArgue();
        beans.agreement = rl_voiceView.getArgue2();
        beans.performance = rl_voiceView.getPerformance();
        beans.signature = rl_voiceView.getSignature();
        beans.num = rl_voiceView.getNumber();
        return beans;
    }

    private void saveAndCreate(NewOralBeans bean){
        NewOralModel model = new NewOralModel(bean);
        model.setCallBackListener(new BaseModel.CallBackListener<PostRequestBean>() {
            @Override
            public void success(PostRequestBean bean) {
                ToastUtils.showShort(NewOralActivity.this,bean.data);
                if(bean.code == 1){
                    finish();
                }
            }
            @Override
            public void failed() {

            }
        });
        model.postOral();
    }



    private void next() {
        beans = getBean();
        if(!TextUtils.isEmpty(audit)&&audit.equals("1")){
            ToastUtils.showShort(NewOralActivity.this,"审核已经通过，不能操作");
            return;
        }
        if(TextUtils.isEmpty(search)){
            //新增
           saveAndCreate(beans);
        }else {
                ModifyOralModel modifyOralModel = new ModifyOralModel(beans);
                modifyOralModel.setCallBackListener(new BaseModel.CallBackListener<PostRequestBean>() {
                    @Override
                    public void success(PostRequestBean postRequestBean) {
                        ToastUtils.showShort(NewOralActivity.this,postRequestBean.data);
                        if(postRequestBean.code == 1){
                            finish();
                        }
                    }
                    @Override
                    public void failed() {

                    }
                });
                modifyOralModel.modify();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(handler!=null){
            handler.removeCallbacksAndMessages(null);
            handler=null;
        }
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()){
            case R.id.tv_evidence_entering:
                Intent intent = new Intent(this,EvidenceEnteringActivity.class);
                intent.putExtra("id",caseId);
                IntentUtils.startActivity(NewOralActivity.this,intent);
                break;
            case R.id.tv_add:
                CommonDialog dialog = new CommonDialog(NewOralActivity.this);
                dialog.setListener(new CommonDialog.SelectTypeListener() {
                    @Override
                    public void click(int type) {
                        switch (type){
                            case 0:
                                Intent intent1 = new Intent(NewOralActivity.this,AddOnePersonActivity.class);
                                IntentUtils.startActivity(NewOralActivity.this,intent1,true,1);
                                break;
                            case 1:
                                intent1 = new Intent(NewOralActivity.this,AddTwoPersonActivity.class);
                                IntentUtils.startActivity(NewOralActivity.this,intent1,true,2);
                                break;
                            case 2:
                                intent1 = new Intent(NewOralActivity.this,AddThreePersonActivity.class);
                                IntentUtils.startActivity(NewOralActivity.this,intent1,true,3);
                                break;
                        }
                    }
                });
                dialog.show();
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(data == null){
            return;
        }
        switch (requestCode){
            case 1:
                switch (resultCode){
                    case 1:
                        NewOralBean bean = (NewOralBean) data.getSerializableExtra("bean");
                        bean.type = "1";
                        updateList(bean);
                        break;
                    case 10:
                        bean = (NewOralBean) data.getSerializableExtra("bean");
                        int position = data.getIntExtra("position",-1);
                        if(position!=-1){
                            update(position,bean);
                        }
                        break;
                }
                break;
            case 2:
                switch (resultCode){
                    case 2:
                        NewOralBean bean = (NewOralBean) data.getSerializableExtra("bean");
                        bean.type = "2";
                        updateList(bean);
                        break;
                    case 20:
                        bean = (NewOralBean) data.getSerializableExtra("bean");
                        int position = data.getIntExtra("position",-1);
                        if(position!=-1){
                            update(position,bean);
                        }
                        break;
                }
                break;
            case 3:
                switch (resultCode){
                    case 3:
                        NewOralBean bean = (NewOralBean) data.getSerializableExtra("bean");
                        bean.type = "3";
                        updateList(bean);
                        break;
                    case 30:
                        bean = (NewOralBean) data.getSerializableExtra("bean");
                        int position = data.getIntExtra("position",-1);
                        if(position!=-1){
                            update(position,bean);
                        }
                        break;
                }
                break;
        }
    }
    private void update(int position,NewOralBean bean){
        list.remove(position);
        list.add(position,bean);
        NewOralAdapter  adapter = new NewOralAdapter(this,list);
        listView.setAdapter(adapter);

    }

    private void updateList(NewOralBean bean){
        if(list == null){
            list = new ArrayList<>();
        }
        list.add(bean);
        NewOralAdapter  adapter = new NewOralAdapter(this,list);
        listView.setAdapter(adapter);
    }
}